package com.techsoul.module.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelExport;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.StoreMapper;
import com.techsoul.module.basic.pojo.vo.StoreVo;
import com.techsoul.module.basic.service.IStoreService;
import com.techsoul.module.goods.enmus.SpuStatusEnum;
import com.techsoul.module.goods.mapper.SpuMapper;
import com.techsoul.module.goods.pojo.entity.Spu;
import com.techsoul.module.order.enmus.ReturnOrderStatusEnum;
import com.techsoul.module.order.mapper.PriceTrackMapper;
import com.techsoul.module.order.mapper.ReturnOrderItemMapper;
import com.techsoul.module.order.pojo.entity.PriceTrack;
import com.techsoul.module.order.pojo.entity.ReturnOrderItem;
import com.techsoul.module.order.pojo.param.SalesOrderSaveParam;
import com.techsoul.module.order.enmus.SalesOrderSourceEnum;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.enmus.SalesOrderTypeEnum;
import com.techsoul.module.order.mapper.SalesOrderItemMapper;
import com.techsoul.module.order.mapper.SalesOrderMapper;
import com.techsoul.module.order.pojo.entity.SalesOrder;
import com.techsoul.module.order.pojo.entity.SalesOrderItem;
import com.techsoul.module.order.pojo.param.SalesOrderItemSaveParam;
import com.techsoul.module.order.pojo.param.SalesOrderItemSearchParam;
import com.techsoul.module.order.pojo.vo.*;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.service.ICustomerService;
import com.techsoul.module.order.service.ISalesOrderItemService;
import com.techsoul.module.pms.mapper.CustGoodsMapMapper;
import com.techsoul.module.pms.mapper.GoodsGroupMapper;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.pms.pojo.entity.CustGoodsMap;
import com.techsoul.module.pms.pojo.entity.GoodsGroup;
import com.techsoul.module.goods.pojo.entity.Sku;
import com.techsoul.module.pms.pojo.param.CustGoodsMapSaveParam;
import com.techsoul.module.pms.pojo.vo.CustGoodsMapVo;
import com.techsoul.module.system.enmus.ErrorType;
import com.techsoul.module.system.mapper.OperationLogMapper;
import com.techsoul.module.system.pojo.entity.OperationLog;
import com.techsoul.module.system.service.IConfigService;
import com.techsoul.module.system.service.IGeneralSeqService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.springframework.util.unit.DataSize.parse;

/**
 * 销售订单明细 Service实现
 *
 * @author liuen
 * @date 2020-12-07
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class SalesOrderItemServiceImpl implements ISalesOrderItemService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SalesOrderItemMapper mapper;
    @Autowired
    private ReturnOrderItemMapper rtitemmapper;
    @Autowired
    private IGeneralSeqService generalSeqService;

    @Autowired
    private PriceTrackMapper priceTrackmapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private SalesOrderMapper orderMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private ICustomerService iCustomerService;

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private IStoreService iStoreService;

    @Autowired
    private CustGoodsMapMapper custGoodsMapMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private GoodsGroupMapper goodsGroupMapper;

    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(SalesOrderItemSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItem entity = new SalesOrderItem();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        if (StringUtils.isBlank(entity.getSpuId())) {
            entity.setSpuId(params.getGoodsId());
        }
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        SalesOrderItem salesOrderItem = new SalesOrderItem();
        salesOrderItem.setIsValid(ApiConstants.N)
                .setId(id);
        return this.mapper.updateById(salesOrderItem);
    }

    /**
     * 根据订单ID逻辑删除
     * @param orderId
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public void deleteByOrderId(String orderId) {
        UpdateWrapper<SalesOrderItem> uw = new UpdateWrapper<>();
        uw.eq("sales_order_id", orderId);
        SalesOrderItem salesOrderItem = new SalesOrderItem();
        salesOrderItem.setIsValid(ApiConstants.N);
        this.mapper.update(salesOrderItem, uw);
    }

    /**
     * 批量逻辑删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public void batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            idList.forEach(id -> this.delete(id));
        }
    }

    @Transactional(readOnly = false)
    @Override
    public String suppierReportDepart(Map map) {
        String supplierNo = (String) map.get("supplierNo");
        String orderItemNo = (String) map.get("orderItemNo");
        String shipmentNo = (String) map.get("shipmentNo");

        String departTime = (String) map.get("departTime");
        SalesOrderItemSearchParam salesOrderItemSearchParam = new SalesOrderItemSearchParam();
        salesOrderItemSearchParam.setCustSalesOrderItemNo(orderItemNo);
        List<SalesOrderItemVo> retresult = this.findAll(salesOrderItemSearchParam);
        for (int i = 0; i < retresult.size(); i++) {
            SalesOrderItemVo salesOrderItem = (SalesOrderItemVo) retresult.get(i);
           salesOrderItem.setSupplierStatus(SalesOrderStatusEnum.DELIVERED.getValue());
            salesOrderItem.setDeliveryAddTime(departTime);
            salesOrderItem.setPickUpCode(shipmentNo);
            SalesOrderItem entityFromDb = this.mapper.selectById(salesOrderItem.getId());
            if (entityFromDb == null) {
                throw new ParamException("id=" + salesOrderItem.getId());
            }
            BeanUtils.copyProperties(salesOrderItem, entityFromDb);
            entityFromDb.preUpdate(supplierNo);
            this.mapper.updateById(entityFromDb);
        }
        return  "success";
    }
    /**
     * 修改
     * @param id
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(String id, SalesOrderItemSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItem entityFromDb = this.mapper.selectById(id);
        if (entityFromDb == null) {
            throw new ParamException("id=" + id);
        }
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    @Transactional(readOnly = false)
    @Override
    public Integer updateFromAsnc(String id, SalesOrderItemSaveParam params,UserVo userVo) {

        SalesOrderItem entityFromDb = this.mapper.selectById(id);
        if (entityFromDb == null) {
            throw new ParamException("id=" + id);
        }
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(userVo.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 修改
     * @param id
     *
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer importAgain(String id) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItem entityFromDb = this.mapper.selectById(id);
        SalesOrder salesOrder =this.orderMapper.selectById(entityFromDb.getSalesOrderId());
        String importError = " ";
        String errorFlag = "N";
        if (entityFromDb == null) {
            throw new ParamException("id=" + id);
        }
        StoreVo storeVo = null;
        if(!StringUtils.isNull(entityFromDb.getStoreId())){
            String storeCode =this.replaceStoreCode(entityFromDb.getStoreId());

            storeVo = storeMapper.findByCode(storeCode);
            if(storeVo!=null){
                salesOrder.setStoreId(storeVo.getStoreCode());
            }else{
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
                operationLog.setErrorMsg(entityFromDb.getCustSalesOrderNo()+"店铺基础数据没有维护");
                operationLog.setMethod("导入模板-原始订单-批量导入");
                operationLog.setLocation(entityFromDb.getSalesOrderItemNo());
                operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);

                importError ="店铺没有查到：".concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                errorFlag="Y";
            }
        }else{
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(entityFromDb.getCustSalesOrderNo()+"店铺基础数据没有提供");
            operationLog.setMethod("导入模板-原始订单-批量导入");
            operationLog.setLocation(entityFromDb.getSalesOrderItemNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            importError ="店铺数据原始订单未提供：".concat(operationLog.getLocation()).concat(operationLog.getErrorMsg());
            errorFlag="Y";
        }
        CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(entityFromDb.getCustSpuId(),entityFromDb.getCustSkuId(),storeVo.getMallId());
        if(custGoodsMapVo==null){
            custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(entityFromDb.getCustSpuId(),"通用",storeVo.getMallId());

        }
        if(custGoodsMapVo==null){//映射表内没有
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(entityFromDb.getCustSalesOrderNo()+"商品价格不存在本系统，请先导入商品价格 ");
            operationLog.setMethod("导入模板-原始订单-批量导入");
            operationLog.setLocation(entityFromDb.getSalesOrderItemNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            entityFromDb.setErrorFlag("Y");
            importError=importError.concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
        }else{
            entityFromDb.setSpuId(custGoodsMapVo.getSpuId());
            entityFromDb.setSkuId(custGoodsMapVo.getSkuId());
            entityFromDb.setMaterialMapId(custGoodsMapVo.getId());
        }
        salesOrder.setErrorFlag(errorFlag);
        salesOrder.setImportErrorMesg(importError);
        salesOrder.preUpdate(user.getId());
        salesOrder.setStoreId(entityFromDb.getStoreId());
        this.orderMapper.updateById(salesOrder);
        entityFromDb.setErrorFlag(errorFlag);
        entityFromDb.setImportErrorMesg(importError);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }
    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public SalesOrderItemVo findById(String id) {
        SalesOrderItemVo salesOrderItemVo = this.mapper.findById(id);
        return salesOrderItemVo;
    }

    @Override
    public SalesOrderItemVo findByCustSalesOrderItemNo(String custSalesOrderItemNo) {
        SalesOrderItemVo salesOrderItemVo = this.mapper.findByCustSalesOrderItemNo(custSalesOrderItemNo);
        return salesOrderItemVo;
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<SalesOrderItemVo> findAll(SalesOrderItemSearchParam params) {
        if(!StringUtils.isNull(params.getStatus())){
            if(params.getStatus().equals("0")){
                params.setStatus(null);
            }
        }
        List<SalesOrderItemVo> orderItemVos = this.mapper.findAll(params);
        return orderItemVos;
    }
    /**
     * 品牌排行列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    // @Override
    //  public IPage<SalesOrderItemBrandRateViewVo> brandRateView(SalesOrderItemSearchParam params, Integer current, Integer pageSize){
    //      return this.mapper.brandRateView(new Page<>(current, pageSize), params);
    //  }

    /**
     * 供应商排行列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    //   @Override
    //   public IPage<SalesOrderItemSupplierRateViewVo> supplierRateView(SalesOrderItemSearchParam params, Integer current, Integer pageSize) {
    //      return this.mapper.supplierRateView(new Page<>(current, pageSize), params);
    //  }
    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<SalesOrderItemVo> findAll(SalesOrderItemSearchParam params, Integer current, Integer pageSize) {
        if(!StringUtils.isNull(params.getStatus())){
            if(params.getStatus().equals("0")){
                params.setStatus(null);
            }
        }
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    /**
     * 单品销售列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<SalesOrderItemVo> skuRateView(SalesOrderItemSearchParam params, Integer current, Integer pageSize) {

        return this.mapper.skuRateView(new Page<>(current, pageSize), params);
    }
    /**
     * 导入模板
     */
    @Override
    public String importTemplate() {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "导入模板-原始订单-批量导入.xlsx";
        try {
            new ExcelExport(null, SalesOrderItemVo.class).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("生成供应商采购价格导入模板失败", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }

    /**
     * 读取MQ
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String readMq(SalesOrderSaveParam params) {
        List<SalesOrderItemSaveParam> dataList = params.getItems();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        CustomerVo customerVo = iCustomerService.findById(params.getCustomerId());

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;


        if(dataList==null||dataList.size()==0){
            return "没有读取到数据";
        }
        SalesOrderItemSaveParam firstdata = (SalesOrderItemSaveParam)dataList.get(0);

        String custOrderNo ="";
        SalesOrder newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        List<String> custOrderNos = new ArrayList<String>();
        for (SalesOrderItemSaveParam sitem : dataList) {
            SalesOrderItemVo data  = new SalesOrderItemVo();
            BeanUtils.copyProperties(sitem, data);
            data = this.removeSpecialChar(data);
            line++;
            // if(!data.getCustSalesOrderNo().equals(custOrderNo)){
            custOrderNo =data.getCustSalesOrderNo();
            if(!custOrderNos.contains(custOrderNo)){
                itemNo = 0;
                newSalesOrder = this.addNewSalesOrder(data,user,customerVo,line);
                if(newSalesOrder!=null){
                    //custOrderNo = data.getCustSalesOrderNo();
                    custOrderNos.add(custOrderNo);
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }
            }

            itemNo = itemNo++;
            if(newSalesOrder!=null){
                SalesOrderItem salesOrderItem = this.addNewItem(newSalesOrder,data,user,itemNo,line);
                if(salesOrderItem!=null){
                    successNum++;
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }
            }



        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误清查日志");
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setMethod("导入模板-原始订单-批量导入");
            operationLog.setLocation("第"+line+"行");
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            // throw new ExcelException(failureMsg.toString());
            return "操作有"+failureNum+"行输入异常，请看日志";
        } else {
            if(logNum>0){
                successMsg.insert(0, "恭喜您，操作成功！共 " + successNum + " 条，另有：" +logNum+ " 条数据不能正常导入，已写入日志");

            }else{
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

            }
        }
        return successMsg.toString();
    }
    /**
     * 退单登记
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String createReturn(SalesOrderItemSaveParam params){
        Integer qty =  params.getReturnQty();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String id = params.getId();
        SalesOrderItem item = this.mapper.findByEntityCustSalesOrderItemNo(id);
        String returnOrderNo = this.generalSeqService.generateSeq("oms_return_order");
        //  item.setReturnQty(qty);
        //  item.setReturnOrderItemNo(returnOrderNo);
        // item.setStatus(SalesOrderStatusEnum.RETURN_APPLIED.getValue());
        //this.mapper.updateById(item);
        ReturnOrderItem rtitem = new ReturnOrderItem();
        rtitem.setQty(new Long(qty));
        rtitem.setSalesOrderItemId(id);
        rtitem.setSkuId(item.getSkuId());
        rtitem.setCustSalesOrderNo(item.getCustSalesOrderNo());
        rtitem.setCustSalesOrderItemNo(item.getCustSalesOrderItemNo());
        rtitem.setCustSkuId(item.getCustSkuId());
        rtitem.setReturnOrderId(returnOrderNo);

        rtitem.setSpuId(item.getSpuId());
        rtitem.setStoreId(item.getStoreId());
        rtitem.setStoreName(item.getStoreName());
        rtitem.setCustReturnOrderStatus(ReturnOrderStatusEnum.NEWREC.getValue());
        rtitem.setStatus(ReturnOrderStatusEnum.NEWREC.getValue());
        rtitem.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        this.rtitemmapper.insert(rtitem);
        return "success";
    }

    /**
     * 历史数据导入
     * @param file
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String dataMigration(String customerNo, MultipartFile file){
        List<SalesOrderItemVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        CustomerVo customerVo = iCustomerService.findById(customerNo);

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(SalesOrderItemVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            return "没有读取到数据";
        }
        SalesOrderItemVo firstdata = (SalesOrderItemVo)dataList.get(0);
        String custOrderNo ="";
        SalesOrder newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        List<String> custOrderNos = new ArrayList<String>();
        for (SalesOrderItemVo data : dataList) {
            data = this.removeSpecialChar(data);
            line++;
            // if(!data.getCustSalesOrderNo().equals(custOrderNo)){
            custOrderNo =data.getCustSalesOrderNo();
            if(!custOrderNos.contains(custOrderNo)){
                itemNo = 0;
                newSalesOrder = this.addMigrationSalesOrder(data,user,customerVo,line);
                if(newSalesOrder!=null){
                    //custOrderNo = data.getCustSalesOrderNo();
                    custOrderNos.add(custOrderNo);
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }
            }

            itemNo = itemNo++;
            if(newSalesOrder!=null){
                SalesOrderItem salesOrderItem = this.addMigrationItem(newSalesOrder,data,user,itemNo,line);
                if(salesOrderItem!=null){
                    successNum++;
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }
            }



        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误清查日志");
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setMethod("导入模板-原始订单-批量导入");
            operationLog.setLocation("第"+line+"行");
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            // throw new ExcelException(failureMsg.toString());
            return "操作有"+failureNum+"行输入异常，请看日志";
        } else {
            if(logNum>0){
                successMsg.insert(0, "恭喜您，操作成功！共 " + successNum + " 条，另有：" +logNum+ " 条数据不能正常导入，已写入日志");

            }else{
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

            }
        }
        return successMsg.toString();
    }
    /**
     * 导入
     * @param data
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public SalesOrder importData(String customerNo, SalesOrderItemVo data,String needOrderYn,UserVo user,int itemNo,int line,CustomerVo customerVo, SalesOrder newSalesOrder) {
        data = this.removeSpecialChar(data);


        if (needOrderYn.equals("No")) {
            SalesOrderItem salesOrderItem = this.addNewItem(newSalesOrder, data, user, itemNo, line);
            return newSalesOrder;
        } else {
            SalesOrder salesOrdernext = this.addNewSalesOrder(data, user, customerVo, line);
            SalesOrderItem salesOrderItem = this.addNewItem(salesOrdernext, data, user, itemNo, line);
            return salesOrdernext;
        }
    }
           //     itemNo = 0;

      /*          if(newSalesOrder!=null){
                    custOrderNo = data.getCustSalesOrderNo();
                    custOrderNos.add(custOrderNo);
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }*/


          //  itemNo = itemNo++;
     //       if(newSalesOrder!=null){

      //          if(salesOrderItem!=null){
      //              successNum++;
      //          }else{
       //             failureNum++;
       //             logNum++;
      //              continue;
       //         }
     //       }

//
      //  }

     //   return successMsg.toString();
   // }

    /**
     * 从mq导入
     * @param salesOrderItemVo
     */
    @Transactional(readOnly = false)
    @Override
    public String importOrderFromMq(SalesOrderItemVo salesOrderItemVo,String customerNo) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        String failureMsg = " ";
        CustomerVo customerVo = iCustomerService.findByCode(customerNo);
        if(customerVo == null){
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg("客户商城不存在");
            operationLog.setMethod("读取队列订单");
            operationLog.setId(idWorker.nextId() + "").preInsert(ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            return "客户商城不存在";
        }
        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;

        salesOrderItemVo = this.removeSpecialChar(salesOrderItemVo);
        String  custSalesOrderItemNo =salesOrderItemVo.getCustSalesOrderItemNo();
        SalesOrder newSalesOrder = this.addNewSalesOrder(salesOrderItemVo, null,customerVo,1);

        if (newSalesOrder == null) {
            failureMsg="很抱歉，导入失败！";
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setMethod("读取队列订单");
            operationLog.setLocation("客户子订单号"+custSalesOrderItemNo);
            operationLog.setId(idWorker.nextId() + "").preInsert(ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            return failureMsg;

        }
        SalesOrderItem salesOrderItem = this.addNewItem(newSalesOrder,salesOrderItemVo,null,1,1);
        if (salesOrderItem == null) {
            failureMsg="很抱歉，导入失败！";
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setMethod("读取队列订单");
            operationLog.setLocation("客户子订单号"+custSalesOrderItemNo);
            operationLog.setId(idWorker.nextId() + "").preInsert(ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            return failureMsg;

        }

        return "success";
    }

    @Transactional(readOnly = false)
    @Override
    public SalesOrder addNewSalesOrder(SalesOrderItemVo salesOrderItemVo,UserVo user,CustomerVo customerVo,int line) {

        SalesOrder salesOrder = new SalesOrder();
        String importError = "";
        String errorFlag="N";
        if(!StringUtils.isNull(salesOrderItemVo.getStoreId())){
            String storeCode =this.replaceStoreCode(salesOrderItemVo.getStoreId());
            StoreVo storeVo = storeMapper.findByCode(storeCode);

            salesOrder.setStoreId(storeCode);
            if(storeVo!=null){
                salesOrder.setStoreId(storeVo.getStoreCode());
            }else{
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
                operationLog.setErrorMsg(salesOrderItemVo.getCustSalesOrderItemNo()+"店铺基础数据没有维护");
                operationLog.setMethod("601");
                operationLog.setLocation("子订单号:".concat(salesOrderItemVo.getCustSalesOrderItemNo()));
                operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);

                importError ="店铺没有查到";
                errorFlag="Y";
            }
        }else{
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(salesOrderItemVo.getCustSalesOrderItemNo()+"店铺基础数据没有提供");
            operationLog.setMethod("601");
            operationLog.setLocation("子订单号:".concat(salesOrderItemVo.getCustSalesOrderItemNo()));

            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            importError ="店铺数据原始订单未提供";
            errorFlag="Y";
        }
       // String orderNo = this.generalSeqService.generateSeq("oms_sales_order");
        salesOrder.setCustSalesOrderNo(salesOrderItemVo.getCustSalesOrderNo());

        salesOrder.setCustomerId(customerVo.getId());
        salesOrder.setCustomerName(customerVo.getCustomerName());
        salesOrder.setDeliveryStatus(salesOrderItemVo.getDeliveryStatus());
        salesOrder.setFreightFee(salesOrderItemVo.getFreightFee());
        salesOrder.setOrderStatus(salesOrderItemVo.getCustOrderStatus());
        salesOrder.setOrderType(SalesOrderTypeEnum.BySku.getValue());
        salesOrder.setPayStatus(salesOrderItemVo.getPaymentStatus());
        salesOrder.setSourceType(SalesOrderSourceEnum.Byexcel.getValue());
        salesOrder.setStoreSource(salesOrderItemVo.getStoreSource());
        salesOrder.setErrorFlag(errorFlag);
        salesOrder.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        salesOrder.setSalesOrderNo(salesOrder.getId());
        this.orderMapper.insert(salesOrder);


        return salesOrder;
        // }else{
        //     OperationLog operationLog =new OperationLog();
        //     operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        //      operationLog.setErrorMsg(salesOrderItemVo.getCustSalesOrderNo()+"订单已经输入，不可重复输入 ");
        //     operationLog.setMethod("导入模板-原始订单-批量导入");
        //     operationLog.setLocation("第"+line+"行");
        //     operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
        //     operationLogMapper.insert(operationLog);
        //    return null;
        // }

    }
    @Transactional(readOnly = false)
    @Override
    public SalesOrder addMigrationSalesOrder(SalesOrderItemVo salesOrderItemVo,UserVo user,CustomerVo customerVo,int line) {

        SalesOrder salesOrder = new SalesOrder();
        String importError = "";
        String errorFlag="N";
        if(!StringUtils.isNull(salesOrderItemVo.getStoreId())){
            String storeCode =this.replaceStoreCode(salesOrderItemVo.getStoreId());
            //   StoreVo storeVo = storeMapper.findByCode(storeCode);

            salesOrder.setStoreId(storeCode);
            //  if(storeVo!=null){
            //      salesOrder.setStoreId(storeVo.getStoreCode());
            //  }else{

            //   }
        }else{

        }
        String orderNo = this.generalSeqService.generateSeq("oms_sales_order");
        salesOrder.setCustSalesOrderNo(salesOrderItemVo.getCustSalesOrderNo());
        salesOrder.setSalesOrderNo(orderNo);
        salesOrder.setCustomerId(customerVo.getId());
        salesOrder.setCustomerName(customerVo.getCustomerName());
        salesOrder.setDeliveryStatus(salesOrderItemVo.getDeliveryStatus());
        salesOrder.setFreightFee(salesOrderItemVo.getFreightFee());
        salesOrder.setOrderStatus(salesOrderItemVo.getCustOrderStatus());
        salesOrder.setOrderType(SalesOrderTypeEnum.BySku.getValue());
        salesOrder.setPayStatus(salesOrderItemVo.getPaymentStatus());
        salesOrder.setSourceType(SalesOrderSourceEnum.Byexcel.getValue());
        salesOrder.setStoreSource(salesOrderItemVo.getStoreSource());
        salesOrder.setErrorFlag(errorFlag);
        salesOrder.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        this.orderMapper.insert(salesOrder);


        return salesOrder;


    }
    private String replaceStoreCode(String storeCode){
        String rtStore = "贸易";
        if(storeCode.contains("南航贸易")){
            storeCode =storeCode.trim();
            String num = storeCode.substring(4);
            String lastnum = "";
            if(num.length()==1){
                lastnum = "00".concat(num);
            }else if(num.length()==2){
                lastnum = "0".concat(num);
            }else{
                lastnum=num;
            }
            rtStore = rtStore.concat(lastnum);
        }else{
            rtStore = storeCode;
        }
        return rtStore;
    }
    @Transactional(readOnly = false)
    @Override
    public SalesOrderItem addNewItem(SalesOrder newSalesOrder, SalesOrderItemVo data,UserVo user,int itemNo,int line){

        SalesOrderItem salesOrderItem = new SalesOrderItem();
        salesOrderItem.setErrorFlag(newSalesOrder.getErrorFlag());
        if(!StringUtils.isNull(newSalesOrder.getErrorCode())){
            salesOrderItem.setErrorCode(newSalesOrder.getErrorCode());
            if(newSalesOrder.getErrorCode().equals("101")){
                salesOrderItem.setErrorFlag("Y");
            }
        }
        String errorMsg = newSalesOrder.getImportErrorMesg();
        String itemErrorMsg = "明细保存：";
        BeanUtils.copyProperties(data, salesOrderItem);
        List<SalesOrderItem> salesOrderItems =this.mapper.findByCustSalesOrderItemNoAndOrProductSkuCode(data.getCustSalesOrderItemNo(),data.getCustSkuId());

        if(salesOrderItems!=null&&salesOrderItems.size()>0){

            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg("订单已经输入，不可重复输入 ");
            operationLog.setMethod("101");
            operationLog.setLocation(data.getCustSalesOrderNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            if(!StringUtils.isNull(errorMsg)){
                errorMsg =
                        errorMsg.concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                // salesOrderItem.setImportErrorMesg(errorMsg);
                salesOrderItem.setErrorFlag("Y");
            }else{
                // salesOrderItem.setImportErrorMesg(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                errorMsg = "订单已经输入，不可重复输入 ";
                salesOrderItem.setErrorFlag("Y");
            }
            itemErrorMsg = itemErrorMsg.concat(errorMsg);
            salesOrderItem.setErrorCode("101");
            salesOrderItem.setErrorFlag("Y");
        }


        StoreVo storeVo=null;
        if(StringUtils.isNull(data.getStoreId())){

            salesOrderItem.setGenAccFailedReason("店铺数据没有维护 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("601"));
            }else{
                salesOrderItem.setErrorCode("601");
            }
            this.genOperationLog(salesOrderItem,user);
            itemErrorMsg=itemErrorMsg.concat("店铺数据没有维护 ");
        }else{
            String storeCode =this.replaceStoreCode(data.getStoreId());
            storeVo = storeMapper.findByCode(storeCode);
            salesOrderItem.setStoreId(storeCode);
        }
        if(storeVo==null){

            salesOrderItem.setGenAccFailedReason("店铺数据没有维护 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("601"));
            }else{
                salesOrderItem.setErrorCode("601");
            }
            this.genOperationLog(salesOrderItem,user);

            itemErrorMsg=itemErrorMsg.concat("店铺数据没有维护 ");
        }
        salesOrderItem.setSalesOrderNo(newSalesOrder.getSalesOrderNo());
        salesOrderItem.setSalesOrderId(newSalesOrder.getId());
        salesOrderItem.setSalesOrderItemNo(String.valueOf(itemNo));
        salesOrderItem.setCustomerNo(newSalesOrder.getCustomerId());
        salesOrderItem.setCustomerName(newSalesOrder.getCustomerName());
        salesOrderItem.setCustSkuId(data.getCustSkuId());
        salesOrderItem.setCustSpuId(data.getCustSpuId());
        CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),data.getCustSkuId(),newSalesOrder.getCustomerId());
        if(custGoodsMapVo==null){
            custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),"通用",newSalesOrder.getCustomerId());
        }
        if(custGoodsMapVo==null){//映射表内没有

            salesOrderItem.setGenAccFailedReason("商品价格不存在本系统，请先导入商品价格 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("201"));
            }else{
                salesOrderItem.setErrorCode("201");
            }
            this.genOperationLog(salesOrderItem,user);

            itemErrorMsg=itemErrorMsg.concat("商品价格不存在本系统，请先导入商品价格 ");
        }else{
            salesOrderItem.setSpuId(custGoodsMapVo.getSpuId());
            salesOrderItem.setSkuId(custGoodsMapVo.getSkuId());
            salesOrderItem.setMaterialMapId(custGoodsMapVo.getId());

        }
     /*   if(!StringUtils.isNull(data.getCustSpuId())){
            List<CustGoodsMapVo> cgms = custGoodsMapMapper.findByCustGoodNo(data.getCustSpuId(),storeVo.getMallId());
            if(cgms==null||cgms.size()==0) {  //映射表内没有
                Spu newspu = this.genAddGood(data,user);
                salesOrderItem.setSpuId(newspu.getId());
                // salesOrderItem.setSkuId(custGoodsMap.getSkuId());
                OperationLog operationLog =new OperationLog();
                operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatus());
                operationLog.setErrorMsg(data.getCustSalesOrderNo()+"商品价格不存在本系统，请先导入商品价格 ");
                operationLog.setMethod("导入模板-原始订单-批量导入");
                operationLog.setLocation("第"+line+"行");
                operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
                if (user != null) {
                    operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
                }
                operationLogMapper.insert(operationLog);
                CustGoodsMapVo cgm = custGoodsMapMapper.findByCustSkuNo(data.getCustSkuId(),storeVo.getMallId());
                if(cgm==null){
                    Sku sku = this.genAddGoodSku(data,user,newspu);
                    salesOrderItem.setSkuId(sku.getId());

                }else{
                    salesOrderItem.setSkuId(cgm.getSkuId());
                    salesOrderItem.setMaterialMapId(cgm.getId());
                }
            }else{

                CustGoodsMapVo skucgm = custGoodsMapMapper.findByCustSkuNo(data.getCustSkuId(),storeVo.getMallId());
                if(skucgm==null){
                    CustGoodsMapVo cgm = null;
                    Spu spu= null;
                    for(int j=0;j<cgms.size();j++){
                        cgm =  (CustGoodsMapVo)cgms.get(j);
                        salesOrderItem.setSpuId(cgm.getSpuId());
                        spu = spuMapper.findBySpuId(cgm.getSpuId());
                        if(cgm.getSkuId()==null){
                            break;
                        }
                    }
                    Sku sku  = this.genAddGoodSku(data,user,spu);
                    salesOrderItem.setSkuId(sku.getId());
                    String mapid = cgm.getId();
                    salesOrderItem.setMaterialMapId(mapid);

                }else{
                    salesOrderItem.setSkuId(skucgm.getSkuId());
                    salesOrderItem.setMaterialMapId(skucgm.getId());
                }
            }
        }*/
        if(data.getQty()==null){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数为空 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(String.valueOf(data.getQty()).contains(".")){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(data.getQty()<0) {
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");

            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
        if(StringUtils.isNull(data.getCustSpuId())){
            //||StringUtils.isNull(data.getCustSkuId())
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("100"));
            }else{
                salesOrderItem.setErrorCode("100");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg = itemErrorMsg.concat("对方商品ID为空");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
   /*     try{
            double test =  Double.valueOf(data.getCustRelSalesPrice());
            if(test<=0.0){
                if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                    salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("104"));
                }else{
                    salesOrderItem.setErrorCode("104");
                }
                salesOrderItem.setErrorFlag("Y");
                salesOrderItem.setImportErrorMesg("与营销委结算价格不准确，为字符或负数");
            }
        }catch(Exception e){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("104"));
            }else{
                salesOrderItem.setErrorCode("104");
            }
            salesOrderItem.setErrorFlag("Y");
            salesOrderItem.setImportErrorMesg("与营销委结算价格不准确，为字符或负数");
        } */
        List<SalesOrderItemVo> beforesalesOrderItems =new ArrayList<SalesOrderItemVo>();
        if(!StringUtils.isNull(data.getDiscountActivityCode())) {

            beforesalesOrderItems = this.mapper.findBySkuCodeWithActcode(data.getCustSkuId(), data.getDiscountActivityCode());

        }else{
            beforesalesOrderItems =this.mapper.findBySkuCode(data.getCustSkuId());
        }
        if(beforesalesOrderItems!=null&&beforesalesOrderItems.size()>0){
                SalesOrderItemVo bsalesOrderItem = (SalesOrderItemVo)beforesalesOrderItems.get(0);

                Double unitprice = Double.valueOf(data.getCustRelSalesPrice());
                if(!StringUtils.isNull(bsalesOrderItem.getCustRelSalesUnitPrice())){
                    Double oldunitprice = Double.valueOf(bsalesOrderItem.getCustRelSalesUnitPrice());
                    if(!oldunitprice.equals(unitprice)){
                        PriceTrack priceTrack = new PriceTrack();
                        priceTrack.setCity(data.getCustSkuId());
                        priceTrack.setAddress(data.getSkuName());
                        priceTrack.setPhone(data.getCustRelSalesPrice());
                        priceTrack.setName(data.getCustSalesOrderItemNo());

                        priceTrack.setUserId(bsalesOrderItem.getCustSalesOrderItemNo());
                        priceTrack.setDistrict(String.valueOf(bsalesOrderItem.getCustRelSalesUnitPrice()));
                        priceTrack.setId(idWorker.nextId() + "").preInsert(user.getId());
                        this.priceTrackmapper.insert(priceTrack);
                    }
                }
        }






        salesOrderItem.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if(StringUtils.isNull(salesOrderItem.getStatus())){
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        }

        salesOrderItem.setOriginalQty(data.getQty());
        if(storeVo!=null){
            salesOrderItem.setSupplierNo(storeVo.getSupplierId());
            salesOrderItem.setSupplierName(storeVo.getSupplierName());
            salesOrderItem.setStoreName(storeVo.getStoreName());
        }else{
            salesOrderItem.setSupplierNo("");
            salesOrderItem.setSupplierName("");
            salesOrderItem.setStoreName("");
        }


        if(StringUtils.isNull(salesOrderItem.getErrorFlag())){
            salesOrderItem.setErrorFlag("N");
        }
        if(!StringUtils.isNull(data.getOrderTime())){
            Date jobdt= DateUtils.parseDate(data.getOrderTime());
            salesOrderItem.setCreateTime(jobdt);
            salesOrderItem.setOrderTime(DateUtils.formatDateTime(jobdt));
           /* try{
                String datestr= data.getOrderTime();
                Date jobdt=new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(datestr);

                salesOrderItem.setCreateTime(jobdt);
                salesOrderItem.setOrderTime(DateUtils.formatDateTime(jobdt));
            }catch(Exception e){
                if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                    salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("105"));
                }else{
                    salesOrderItem.setErrorCode("105");
                }
             //   salesOrderItem.setErrorFlag("Y");
                itemErrorMsg=itemErrorMsg.concat("日期格式不正确 ");

            }*/

        }
        salesOrderItem.setImportErrorMesg(itemErrorMsg);

        try{
            if(!StringUtils.isNull(data.getCustRelSalesPrice())){
                Double price = NumberUtils.mul(data.getQty().doubleValue(),Double.valueOf(data.getCustRelSalesPrice()));
                salesOrderItem.setCustRelSalesPrice(String.valueOf(price));
                salesOrderItem.setCustRelSalesUnitPrice(Double.valueOf(data.getCustRelSalesPrice()));
            }
            salesOrderItem.setCouponDiscount(data.getCouponDiscount());
            salesOrderItem.setMileageCouponDiscount(data.getMileageCouponDiscount());
            salesOrderItem.setSupplierStatus(SalesOrderStatusEnum.CREATED.getValue());
            this.mapper.insert(salesOrderItem);
        }catch(Exception e){
            log.error("addNewItem error:", e);
            log.error(ToStringBuilder.reflectionToString(data, ToStringStyle.JSON_STYLE));
            salesOrderItem.setImportErrorMesg(e.getMessage().substring(0,49));
            salesOrderItem.setCustSalesOrderNo(String.valueOf(line));
            this.genOperationLog(salesOrderItem,user);
        }


        return salesOrderItem;
    }

    @Transactional(readOnly = false)
    @Override
    public SalesOrderItem addMigrationItem(SalesOrder newSalesOrder, SalesOrderItemVo data,UserVo user,int itemNo,int line){

        SalesOrderItem salesOrderItem = new SalesOrderItem();
        salesOrderItem.setErrorFlag(newSalesOrder.getErrorFlag());
        if(!StringUtils.isNull(newSalesOrder.getErrorCode())){
            salesOrderItem.setErrorCode(newSalesOrder.getErrorCode());
            if(newSalesOrder.getErrorCode().equals("101")){
                salesOrderItem.setErrorFlag("Y");
            }
        }
        String errorMsg = newSalesOrder.getImportErrorMesg();
        String itemErrorMsg = "明细保存：";

        BeanUtils.copyProperties(data, salesOrderItem);
        List<SalesOrderItem> salesOrderItems =this.mapper.findByCustSalesOrderItemNoAndOrProductSkuCode(data.getCustSalesOrderItemNo(),data.getCustSkuId());
        if(salesOrderItems!=null&&salesOrderItems.size()>0){

            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg("订单已经输入，不可重复输入 ");
            operationLog.setMethod("101");
            operationLog.setLocation(data.getCustSalesOrderNo());
            operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            if(!StringUtils.isNull(errorMsg)){
                errorMsg =
                        errorMsg.concat(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                // salesOrderItem.setImportErrorMesg(errorMsg);
                salesOrderItem.setErrorFlag("Y");
            }else{
                // salesOrderItem.setImportErrorMesg(operationLog.getLocation().concat(operationLog.getErrorMsg()));
                errorMsg = "订单已经输入，不可重复输入 ";
                salesOrderItem.setErrorFlag("Y");
            }
            itemErrorMsg = itemErrorMsg.concat(errorMsg);
            salesOrderItem.setErrorCode("101");
            salesOrderItem.setErrorFlag("Y");
        }

        StoreVo storeVo=null;
        if(StringUtils.isNull(data.getStoreId())){

            salesOrderItem.setGenAccFailedReason("店铺数据没有维护 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("601"));
            }else{
                salesOrderItem.setErrorCode("601");
            }
            this.genOperationLog(salesOrderItem,user);
            itemErrorMsg=itemErrorMsg.concat("店铺数据没有维护 ");
        }else{
            String storeCode =this.replaceStoreCode(data.getStoreId());
            storeVo = storeMapper.findByCode(storeCode);
            salesOrderItem.setStoreId(storeCode);
            if(storeVo!=null){
                salesOrderItem.setStoreName(storeVo.getStoreName());
            }
       }

        salesOrderItem.setSalesOrderNo(newSalesOrder.getSalesOrderNo());
        salesOrderItem.setSalesOrderId(newSalesOrder.getId());
        salesOrderItem.setSalesOrderItemNo(String.valueOf(itemNo));
        salesOrderItem.setCustomerNo(newSalesOrder.getCustomerId());
        salesOrderItem.setCustomerName(newSalesOrder.getCustomerName());
        salesOrderItem.setCustSkuId(data.getCustSkuId());
        salesOrderItem.setCustSpuId(data.getCustSpuId());
        CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),data.getCustSkuId(),newSalesOrder.getCustomerId());
        if(custGoodsMapVo==null){
            custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),"通用",newSalesOrder.getCustomerId());
        }
        if(custGoodsMapVo==null){//映射表内没有

            salesOrderItem.setGenAccFailedReason("商品价格不存在本系统，请先导入商品价格 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("201"));
            }else{
                salesOrderItem.setErrorCode("201");
            }
            this.genOperationLog(salesOrderItem,user);

            itemErrorMsg=itemErrorMsg.concat("商品价格不存在本系统，请先导入商品价格 ");
        }else{
            salesOrderItem.setSpuId(custGoodsMapVo.getSpuId());
            salesOrderItem.setSkuId(custGoodsMapVo.getSkuId());
            salesOrderItem.setMaterialMapId(custGoodsMapVo.getId());

        }

        if(data.getQty()==null){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数为空 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(String.valueOf(data.getQty()).contains(".")){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(data.getQty()<0) {
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");

            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
        if(StringUtils.isNull(data.getCustSpuId())){
            //||StringUtils.isNull(data.getCustSkuId())
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("100"));
            }else{
                salesOrderItem.setErrorCode("100");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg = itemErrorMsg.concat("对方商品ID为空");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
        salesOrderItem.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if(StringUtils.isNull(salesOrderItem.getStatus())){
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        }

        salesOrderItem.setOriginalQty(data.getQty());
        if(storeVo!=null){
            salesOrderItem.setSupplierNo(storeVo.getSupplierId());
            salesOrderItem.setSupplierName(storeVo.getSupplierName());
            salesOrderItem.setStoreName(storeVo.getStoreName());
        }else{
            salesOrderItem.setSupplierNo("");
            salesOrderItem.setSupplierName("");
            salesOrderItem.setStoreName("");
        }


        if(StringUtils.isNull(salesOrderItem.getErrorFlag())){
            salesOrderItem.setErrorFlag("N");
        }
        if(!StringUtils.isNull(data.getOrderTime())){
            try{
                String datestr= data.getOrderTime();
                Date jobdt=new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(datestr);

                salesOrderItem.setCreateTime(jobdt);
                salesOrderItem.setOrderTime(DateUtils.formatDateTime(jobdt));
            }catch(Exception e){
                if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                    salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("105"));
                }else{
                    salesOrderItem.setErrorCode("105");
                }
               // salesOrderItem.setErrorFlag("Y");

                itemErrorMsg=itemErrorMsg.concat("日期格式不正确 ");

            }

        }
        salesOrderItem.setImportErrorMesg(itemErrorMsg);

       try{
            if(!StringUtils.isNull(data.getCustRelSalesPrice())){
                Double price = NumberUtils.mul(data.getQty().doubleValue(),Double.valueOf(data.getCustRelSalesPrice()));
                salesOrderItem.setCustRelSalesPrice(String.valueOf(price));
                salesOrderItem.setCustRelSalesUnitPrice(Double.valueOf(data.getCustRelSalesPrice()));
            }
            salesOrderItem.setCouponDiscount(data.getCouponDiscount());
            salesOrderItem.setMileageCouponDiscount(data.getMileageCouponDiscount());
            this.mapper.insert(salesOrderItem);
        }catch(Exception e){
           log.error("addMigrationItem error:", e);
           salesOrderItem.setImportErrorMesg(e.getMessage().substring(0,49));
            salesOrderItem.setCustSalesOrderNo(String.valueOf(line));
            this.genOperationLog(salesOrderItem,user);
        }
        return salesOrderItem;
    }
    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(SalesOrderItem data,UserVo user ) {
        OperationLog operationLog = new OperationLog();
        if(data.getErrorCode().equals("201")||data.getErrorCode().equals("601")){
            operationLog.setOperationType(ErrorType.ACCPROCESSIMPORT.getStatusName());
        }else{
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        }

        String errormsg = " ";
        if(!StringUtils.isNull(data.getGenAccFailedReason())){
            errormsg = errormsg.concat(data.getGenAccFailedReason());
        }
        if(!StringUtils.isNull(data.getImportErrorMesg())){
            errormsg = errormsg.concat(data.getImportErrorMesg());
        }
        operationLog.setErrorMsg(errormsg);
        operationLog.setMethod(data.getErrorCode());
        String orderNo = "子订单号: ".concat(data.getCustSalesOrderItemNo());
        if(!StringUtils.isNull(data.getCustSpuId())){
            orderNo=orderNo.concat(" SPU: ").concat(data.getCustSpuId());
        }
        if(!StringUtils.isNull(data.getCustSkuId())){
            orderNo=orderNo.concat(" SKU: ").concat(data.getCustSkuId());
        }
        if(!StringUtils.isNull(data.getStoreDiscountActId())){
            orderNo=orderNo.concat(" 店铺活动号: ").concat(data.getStoreDiscountActId());
        }
        if(!StringUtils.isNull(data.getDiscountActivityCode())){
            orderNo=orderNo.concat(" 折扣券号: ").concat(data.getDiscountActivityCode());
        }
        if(!StringUtils.isNull(data.getStoreDiscountActId())){
            orderNo=orderNo.concat(" 折扣活动编号: ").concat(data.getStoreDiscountActId());
        }

        operationLog.setLocation(orderNo);
        operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }
    @Transactional(readOnly = false)
    @Override
    public Sku genAddGoodSku(SalesOrderItemVo data,UserVo user,Spu newspu){

        CustGoodsMapSaveParam custGoodsMapSaveParam = new CustGoodsMapSaveParam();
        custGoodsMapSaveParam.setCustGoodsId(data.getCustSkuId());
        // if(data.getGroupOrSpu().equals("单品")){
        Sku newsku = null;
        custGoodsMapSaveParam.setGoodsType("sku");


        if(!StringUtils.isNull(data.getCustSkuId())){
            newsku = this.generateNewSku(data,newspu);
            custGoodsMapSaveParam.setSkuId(newsku.getId());
        }

        custGoodsMapSaveParam.setSpuId(newspu.getId());
        //   this.generateNewGoodsSupplier(data,supplierNo,supplierName,newspu.getId());

        //  }else if(data.getGroupOrSpu().equals("组合")){
        //   custGoodsMapSaveParam.setGoodsType("gp");
        //    GoodsGroup newGoodsGroup = this.generateNewGoodsGroup(data);
        //    custGoodsMapSaveParam.setSpuId(newGoodsGroup.getId());
        //    custGoodsMapSaveParam.setGroupId(newGoodsGroup.getId());
        //     this.generateNewGoodsSupplier(data,supplierNo,supplierName,newGoodsGroup.getId());

        //   }
        CustGoodsMap entity = new CustGoodsMap();
        BeanUtils.copyProperties(custGoodsMapSaveParam, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        custGoodsMapMapper.insert(entity);

        return newsku;


    }
    @Transactional(readOnly = false)
    @Override
    public Spu genAddGood(SalesOrderItemVo data,UserVo user){

        CustGoodsMapSaveParam custGoodsMapSaveParam = new CustGoodsMapSaveParam();
        custGoodsMapSaveParam.setCustGoodsId(data.getCustSpuId());
        Spu newspu = null;
        if(data.getGroupOrSpu().equals("单品")){
            custGoodsMapSaveParam.setGoodsType("spu");

            newspu = this.generateNewSpu(data);
            custGoodsMapSaveParam.setSpuId(newspu.getId());
            //   this.generateNewGoodsSupplier(data,supplierNo,supplierName,newspu.getId());

        }else if(data.getGroupOrSpu().equals("组合")){
            custGoodsMapSaveParam.setGoodsType("gp");
            GoodsGroup newGoodsGroup = this.generateNewGoodsGroup(data);
            newspu = this.generateNewSpu(data);
            custGoodsMapSaveParam.setSpuId(newGoodsGroup.getId());
            custGoodsMapSaveParam.setGroupId(newGoodsGroup.getId());
            //     this.generateNewGoodsSupplier(data,supplierNo,supplierName,newGoodsGroup.getId());

        }
        CustGoodsMap entity = new CustGoodsMap();
        BeanUtils.copyProperties(custGoodsMapSaveParam, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        custGoodsMapMapper.insert(entity);

        return newspu;


    }
    @Override
    public SalesOrderItemVo removeSpecialChar(SalesOrderItemVo input){
        Pattern p =null;
        Matcher m = null;;
        String rt = "";
        if(StringUtils.isNull(input.getGroupOrSpu())||input.getGroupOrSpu()==""){
            input.setGroupOrSpu("单品");
        }else{
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getGroupOrSpu());
            rt = m.replaceAll("");
            input.setGroupOrSpu(rt);
        }
        if(!StringUtils.isNull(input.getCustSalesOrderNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSalesOrderNo());
            rt = m.replaceAll("");
            input.setCustSalesOrderNo(rt);
        }
        if(!StringUtils.isNull(input.getCustSalesOrderItemNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSalesOrderItemNo());
            rt = m.replaceAll("");
            input.setCustSalesOrderItemNo(rt);
        }

        if(!StringUtils.isNull(input.getStoreName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreName());
            rt = m.replaceAll("");
            input.setStoreName(rt);
        }

        if(!StringUtils.isNull(input.getCustSkuId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSkuId());
            rt = m.replaceAll("");
            input.setCustSkuId(rt);
        }

        if(!StringUtils.isNull(input.getCustSpuId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSpuId());
            rt = m.replaceAll("");
            input.setCustSpuId(rt);
        }

        if(!StringUtils.isNull(input.getSpuName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSpuName());
            rt = m.replaceAll("");
            input.setSpuName(rt);
        }
        if(!StringUtils.isNull(input.getStoreName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreName());
            rt = m.replaceAll("");
            input.setStoreName(rt);
        }
        if(!StringUtils.isNull(input.getSupplierName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSupplierName());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }
        if(!StringUtils.isNull(input.getOrderTime())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getOrderTime());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }
        if(!StringUtils.isNull(input.getCustRelSalesPrice())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustRelSalesPrice());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustRelSalesPrice(rt);
            }else{
                rt = rt.substring(1);
                input.setCustRelSalesPrice(rt);
            }
        }
        if(!StringUtils.isNull(input.getCustCashPaymentAmt())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustCashPaymentAmt());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustCashPaymentAmt(rt);
            }else{
                rt = rt.substring(1);
                input.setCustCashPaymentAmt(rt);
            }


        }
        if(!StringUtils.isNull(input.getCustMilePaymentAmt())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustMilePaymentAmt());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustMilePaymentAmt(rt);
            }else{
                rt = rt.substring(1);
                input.setCustMilePaymentAmt(rt);
            }

        }
        if(!StringUtils.isNull(input.getSkuName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSkuName());
            rt = m.replaceAll("");
            input.setSkuName(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryAddTime())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryAddTime());
            rt = m.replaceAll("");
            input.setDeliveryAddTime(rt);
        }
        if(!StringUtils.isNull(input.getStoreDiscountCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreDiscountCode());
            rt = m.replaceAll("");
            input.setStoreDiscountCode(rt);
        }
        if(!StringUtils.isNull(input.getPaymentStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getPaymentStatus());
            rt = m.replaceAll("");
            input.setPaymentStatus(rt);
        }
        if(!StringUtils.isNull(input.getDeliveryStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDeliveryStatus());
            rt = m.replaceAll("");
            input.setDeliveryStatus(rt);
        }
        if(!StringUtils.isNull(input.getCustNote())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustNote());
            rt = m.replaceAll("");
            input.setCustNote(rt);
        }
        if(!StringUtils.isNull(input.getOrderSource())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getOrderSource());
            rt = m.replaceAll("");
            input.setOrderSource(rt);
        }
        if(!StringUtils.isNull(input.getStoreDiscountActId())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreDiscountActId());
            rt = m.replaceAll("");
            input.setStoreDiscountActId(rt);
        }
        if(!StringUtils.isNull(input.getDiscountActivityName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDiscountActivityName());
            rt = m.replaceAll("");
            input.setDiscountActivityName(rt);
        }
        if(!StringUtils.isNull(input.getDiscountActivityCode())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getDiscountActivityCode());
            rt = m.replaceAll("");
            input.setDiscountActivityCode(rt);
        }
        if(!StringUtils.isNull(input.getProductAttribution())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getProductAttribution());
            rt = m.replaceAll("");
            input.setProductAttribution(rt);
        }
        if(!StringUtils.isNull(input.getAfterSaleService())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getAfterSaleService());
            rt = m.replaceAll("");
            input.setAfterSaleService(rt);
        }
        if(!StringUtils.isNull(input.getCustOrderStatus())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustOrderStatus());
            rt = m.replaceAll("");
            input.setCustOrderStatus(rt);
        }
        return input;
    }
    /**
     * 生成商品SKU
     */
    @Override
    public Sku generateNewSku(SalesOrderItemVo materialBuyPriceVo,Spu spu){
        Sku sku = new Sku();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();


        sku.setSpuId(spu.getId());
        sku.setCustSkuId(materialBuyPriceVo.getCustSkuId());
        // sku.setCategoryName(materialBuyPriceVo.getCategoryName());
        // sku.setImage(materialBuyPriceVo.getImage());
        // sku.setSpec(materialBuyPriceVo.getMaterialGuige());
        sku.setSkuName(materialBuyPriceVo.getSkuName());
        sku.setStatus(SpuStatusEnum.CREATED.getStatusName());
        sku.setIsValid("1");
        sku.setId(idWorker.nextId() + "").preInsert(user.getId());
        skuMapper.insert(sku);
        return sku;
    }
    /**
     * 生成商品
     */
    @Override
    public Spu generateNewSpu(SalesOrderItemVo materialBuyPriceVo){
        Spu spu = new Spu();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        spu.setTitle(materialBuyPriceVo.getSkuName());
        spu.setCategoryName(materialBuyPriceVo.getCategoryName());
        spu.setImage(materialBuyPriceVo.getImage());
        spu.setIntroduction(materialBuyPriceVo.getSkuName());
        spu.setSpuName(materialBuyPriceVo.getSkuName());
        spu.setStatus(SpuStatusEnum.CREATED.getStatus());

        spu.setId(idWorker.nextId() + "").preInsert(user.getId());
        spuMapper.insert(spu);
        return spu;
    }
    /**
     * 获得地区订单总数
     *
     * @return
     */
    @Override
    public Integer findTotalOrder(String site) {
        return this.mapper.findTotalOrder(site);
    }

    /**
     * 获得地区当天订单总数
     *
     * @return
     */
    @Override
    public Integer findTotalTodayOrder(SalesOrderItemSearchParam salesOrderItemSearchParam) {
        return this.mapper.findTotalTodayOrder(salesOrderItemSearchParam);
    }
    /**
     * 获得地区订单总数
     *
     * @return
     */
    @Override
    public BigDecimal countTotalSale(SalesOrderItemSearchParam params) {
        return this.mapper.countTotalSale(params);
    }
    /**
     * 获得地区采购总数
     *
     * @return
     */
    @Override
    public BigDecimal countTotalPurchase(SalesOrderItemSearchParam params) {
        return this.mapper.countTotalPurchase(params);
    }

    /**
     * 生成商品组合
     */
    @Override
    public GoodsGroup generateNewGoodsGroup(SalesOrderItemVo materialBuyPriceVo){
        GoodsGroup spu = new GoodsGroup();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        spu.setGoodsGroupName(materialBuyPriceVo.getSkuName());
        spu.setSpuName(materialBuyPriceVo.getSkuName());
        spu.setSpuId(materialBuyPriceVo.getSpuId());
        spu.setId(idWorker.nextId() + "").preInsert(user.getId());
        goodsGroupMapper.insert(spu);
        return spu;
    }
    /**
     *导出问题查询
     *
     * @param params
     * @return
     */
    @Override
    public List<SalesOrderItemFailedVo> findfailed(SalesOrderItemSearchParam params) {
        return this.mapper.findfailed(params);
    }
    @Override
    public String exportData(SalesOrderItemSearchParam params) {
        String baseDir = configService.findByConfigKey("project.attachment.baseDir");
        String baseUrl = configService.findByConfigKey("project.attachment.baseUrl");
        String fileName = "结算失败清单-"+params.getOrderTimeFr().replace("-", "")+ "-"+DateUtils.getDate("yyyyMMdd")+".xlsx";

        List<SalesOrderItemFailedVo> list = this.findfailed(params);
        try {
            new ExcelExport(null, SalesOrderItemFailedVo.class).setDataList(list).writeFile(baseDir + fileName).close();
        } catch (Exception e) {
            log.error("结算清单", e);
            throw new ExcelException(e.getMessage());
        }
        return baseUrl + fileName;
    }
    @Transactional(readOnly = false)
    @Override
    public void fixdata() {
        List<SalesOrderItem> salesOrderItems = this.mapper.selectList(new QueryWrapper<>());
        for (SalesOrderItem salesOrderItem : salesOrderItems) {
            if (StringUtils.isNotBlank(salesOrderItem.getConsigneePhone())) {
                if (StringUtils.isNotBlank(salesOrderItem.getConsigneePhone())) {
                    this.mapper.updateById(salesOrderItem);
                }
            }
        }
    }
}
